layui.use(['jquery', 'authtree', 'form', 'layer'],function(){
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery;
    var authtree = layui.authtree;

    // 初始化
    $.ajax({
        url: '/menu/tree',
        success: function(data){
            //处理返回的data树形数据
            console.log(data.data)
            var jsonStr = JSON.stringify(data.data);
            console.log("jsonStr=======" +jsonStr );
            var menuStr = jsonStr.replace(/children/g,"list");
            console.log(menuStr)
            var menuTree = JSON.parse(menuStr);

            // 渲染时传入渲染目标ID，树形结构数据（具体结构看样例，checked表示默认选中），以及input表单的名字
            authtree.render('#LAY-auth-tree-index', menuTree, {
                inputname: 'menuname',
                layfilter: 'lay-check-auth',
                openall: false,
                autowidth: true,
            });

            // 使用 authtree.on() 不会有冒泡延迟
            authtree.on('change(lay-check-auth)', function(data) {
                var checkedMenuArr = authtree.getChecked('#LAY-auth-tree-index');

            });
        }
    });

    //监听是否启用角色开关
    form.on('switch(switchTest)', function(data){
        if (this.checked) {
            $("#useable").val("0")
        } else {
            $("#useable").val("1")
        }
    });

    form.on("submit(add)",function(data){
        var menuIds = authtree.getChecked('#LAY-auth-tree-index');
        //对data增加数组数据，使得数据的格式副歌springmvc的数组绑定格式
        for (var i = 0;i < menuIds.length;i++) {
            var keyStr = "menuIds" + '['+ i +']';
            data.field[keyStr] = menuIds[i];
        }
        var index = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.8});
        //弹出loading
        $.ajax({
            url: '/role/add',
            type: 'POST',
            data:data.field,
            success: function (data) {
                if(data.code == 200) {
                    top.layer.close(index);
                    top.layer.msg("添加成功！");
                    layer.closeAll("iframe");
                    //刷新父页面
                    parent.location.reload();
                } else {
                    top.layer.close(index);
                    top.layer.msg("添加失败！");
                }
            },
            error:function () {
                top.layer.close(index);
                top.layer.msg("添加失败！");
            }
        });
        return false;
    });

});